package com.qumitech.visualnovel.controller.rest;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.util.ExcelHandler;
import com.qumitech.visualnovel.model.common.BaseResponse;
import com.qumitech.visualnovel.model.dao.console.TaskRecord;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.service.taskrecord.TaskRecordService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
@RequestMapping("/api/commonDownload")
public class CommonDownloadController {
    @Autowired
    TaskRecordService taskRecordService;

    @Autowired
    ExcelHandler excelHandler;

    @RequiresPermissions("commondownload:view")
    @RequestMapping(value="/taskList", method = RequestMethod.GET)
    public JSONObject TaskList(@RequestParam(value="startTime",required=false) String startTime,
                               @RequestParam(value="endTime",required=false) String endTime,
                               @RequestParam(value="offset", required=false, defaultValue="0") int offset,
                               @RequestParam(value="limit", required=false, defaultValue="20") int limit
                               ){

        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        String userName = activeUser.getUsername();
        int count = taskRecordService.CountTaskList(userName,startTime,endTime,offset,limit);
        List<TaskRecord> result =  taskRecordService.ListTask(userName,startTime,endTime,offset,limit);
        BaseResponse results = new BaseResponse(result,count);
        return results;
    }

    @RequiresPermissions("commondownload:view")
    @RequestMapping(value="/download", method = RequestMethod.GET)
    public void TaskDownload(HttpServletResponse response, @RequestParam(value="id") Integer id) {
        TaskRecord taskRecord = taskRecordService.selectByPrimaryKey(id);
        String filePath = taskRecord.getDownloadUrl();
        excelHandler.openExcel(response,filePath);
    }
}
